const mysql = require('mysql');
const mysqlConfig = require('./mysqlconfig.js');

// 获取小于重仓线的所有债券
function wrapGetUnderHeavyPromise(connection) {
  return new Promise((res, rej) => {
    connection.query('SELECT * from convertible_bond_hook WHERE price < heavyline ORDER BY convertible_bond_hook.rating DESC', function(error, results, fields) {
      if (error) {
        rej(error)
      }
      res(results)
    })
  })
}
// 获取大于重仓线小于加仓线的所有债券
function wrapGetBetweenAddAndHeavyPromise(connection) {
  return new Promise((res, rej) => {
    connection.query('SELECT * from convertible_bond_hook WHERE price >= heavyline AND price < addline ORDER BY convertible_bond_hook.rating DESC', function(error, results, fields) {
      if (error) {
        rej(error)
      }
      res(results)
    })
  })
}
// 获取大于加仓线小于建仓线的所有债券
function wrapGetBetweenCreatAndAddPromise(connection) {
  return new Promise((res, rej) => {
    connection.query('SELECT * from convertible_bond_hook WHERE price >= addline AND price < creatline ORDER BY convertible_bond_hook.rating DESC', function(error, results, fields) {
      if (error) {
        rej(error)
      }
      res(results)
    })
  })
}
// 获取大于建仓线的所有债券
function wrapGetBiggerCreatPromise(connection) {
  return new Promise((res, rej) => {
    connection.query('SELECT * from convertible_bond_hook WHERE price >= creatline ORDER BY convertible_bond_hook.rating DESC', function(error, results, fields) {
      if (error) {
        rej(error)
      }
      res(results)
    })
  })
}

async function getTableData() {
  let tableData = null;
  let connection = null;
  try {
    connection = mysql.createConnection({
      ...mysqlConfig,
      charset : 'utf8mb4'
    });
    connection.connect();
    const [uHeavys, bAddHeavys, bCreatAdds, bigerCreats] = await Promise.all([
      wrapGetUnderHeavyPromise(connection),
      wrapGetBetweenAddAndHeavyPromise(connection),
      wrapGetBetweenCreatAndAddPromise(connection),
      wrapGetBiggerCreatPromise(connection),
    ]);
    tableData = {uHeavys, bAddHeavys, bCreatAdds, bigerCreats};
  } catch (error) {
    console.log('error', error);
    tableData = error;
  } finally {
    connection && connection.end();
  }
  return tableData;
}

exports.main_handler = async (event, context, callback) => {
  const tabledatas = await getTableData();
  return tabledatas;
}
